package crazyjava;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SingletonTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Wolf w = Wolf.getInstance();
		System.out.println("Wolf对象创建完毕!");
		Wolf w2=null;
		ObjectOutputStream oos = null;
		ObjectInputStream ois =null;
		System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
		System.out.println(SingletonTest.class.getResource("").getPath());
		try {
			oos = new ObjectOutputStream(new FileOutputStream("E:/TestFile/a.txt"));
			ois = new ObjectInputStream(new FileInputStream("E:/TestFile/a.txt"));
			oos.writeObject(w);
			oos.flush();
			try {
				w2=(Wolf)ois.readObject();
				System.out.println(w.equals(w2));
				System.out.println(w==w2);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(oos!=null){
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(ois!=null){
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}


class Wolf implements Serializable{
	
	private static final long serialVersionUID = -812466725292320586L;
	
	private static Wolf instance;
	
	private String name;
	
	private Wolf(){
		
	}

	public static Wolf getInstance(){
		if(instance==null){
			instance = new Wolf();
		}
		return instance;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Wolf other = (Wolf) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	/*private Object readResolve(){
		return instance; 
	}*/
	
}